package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"home-manager/cache"
	"home-manager/models"
	"time"
)

func List(c *gin.Context) {
	var role []models.Role
	redis_key := "list_error"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&role)
		jsonData, _ := json.Marshal(role)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &role)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var role models.Role
	redis_key := "detail_id" + id

	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).Find(&role)
		jsonData, _ := json.Marshal(role)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &role)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Where("id = ?", id).Debug().Delete(&models.Role{})
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func Add(c *gin.Context) {

}
